package com.center.growcenterserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.center.growcenterserver.common.JwtUtils;
import com.center.growcenterserver.common.R;
import com.center.growcenterserver.mapper.AdminMapper;
import com.center.growcenterserver.model.domain.Admin;
import com.center.growcenterserver.model.domain.Student;
import com.center.growcenterserver.model.request.AdminRequest;
import com.center.growcenterserver.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper,Admin> implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public R verityPasswd(AdminRequest adminRequest, HttpSession session) {
        String username = adminRequest.getUsername();
        String password = adminRequest.getPassword();

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("real_name", username);
        queryWrapper.eq("password", password);

//        调用 MyBatis-Plus 的 selectCount 方法，统计符合条件的记录数。
//        如果记录数大于 0，说明用户名和密码匹配，验证成功。
        if (adminMapper.selectCount(queryWrapper) > 0) {
            session.setAttribute("name", username);
            String tokenStr = JwtUtils.generateToken(adminRequest.getUsername());

            // 查询用户信息，假设username是唯一的，所以使用eq进行精确匹配
            Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("real_name", username));

            // 封装用户信息和token到一个Map或自定义对象中，以便一并返回
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("token", tokenStr);
            resultMap.put("userInfo", admin);

            return R.success("登录成功",resultMap);
        } else {
            return R.error("用户名或密码错误");
        }
    }
}
